package com.bxait;

import com.bxait.utils.ESClientSingle;
import com.bxait.utils.User;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author Chen
 * @description: es插入数据
 * @ClassName ESTest_Client
 * @create 2023-04-08 16:16
 * @Version 1.0
 */
public class ESTest_Doc_Insert {

    public static void main(String[] args) throws IOException {
        // 创建ES的客户端
        RestHighLevelClient client = ESClientSingle.getInstant();

        // 插入数据
        IndexRequest request = new IndexRequest();

        // 设置数据
        request.index("user").id("1001");

        // 需要插入的数据
        User user = new User("zhangSan","男",18);
        // 将数据转化为JSON
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        // 保存数据类型为JSON
        request.source(userJson, XContentType.JSON);

        // 保存数据
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        DocWriteResponse.Result result = response.getResult();
        System.out.println(result);

        // 关闭es客户端
        client.close();
    }

}
